package com.tongtong.controller.sse.controller;

import com.tongtong.controller.sse.service.SseEmitterService;
import com.tt.utils.R;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * SSE长链接
 *
 * @author zl
 * @date 2021/12/13
 */
@Api(tags = "及时通讯")
@RestController
@RequestMapping("/sse")
@Slf4j
public class SseEmitterController {

    @Autowired
    private SseEmitterService sseEmitterService;
    /**
     * 创建SSE长链接
     *
     * @param phone 客户端唯一ID(如果为空，则由后端生成并返回给前端)
     * @return org.springframework.web.servlet.mvc.method.annotation.SseEmitter
     */
    @GetMapping("/CreateSseConnect")
    public SseEmitter createSseConnect(@RequestParam(name = "phone") String phone) {
        String iccid = UUID.randomUUID().toString();
        CompletableFuture<SseEmitter> sseEmitterCompletableFuture = CompletableFuture.supplyAsync(() -> {
            SseEmitter sseConnect = sseEmitterService.createSseConnect( iccid);
            return sseConnect;
        });
        try {
            return sseEmitterCompletableFuture.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发送消息
     *
     * @param clientId 客户端唯一编码
     * @param message  发送内容
     * @return
     */
    @GetMapping("/sendSseMessage")
    public R sendSseMessage(@PathParam("clientId") String clientId, @RequestParam("message") String message) {
        Map<String, Object> maps = new HashMap();
        maps.put("key", message);
        sseEmitterService.sendMsgToClientByClientId(clientId, maps);
        return R.ok();
    }

    /**
     * 关闭SSE连接
     *
     * @param phone 客户端ID
     * @author re
     * @date 2021/12/13
     **/
    @GetMapping("/CloseSseConnect")
    public R closeSseConnect(@RequestParam("phone") String phone,@RequestParam(name = "onlyKey") String onlyKey) {
        String iccid = UUID.randomUUID().toString();
        iccid = iccid+"="+onlyKey;
        sseEmitterService.closeSseConnect(iccid);
        return R.ok();
    }

}

